import json

from common.api import http_result
from user_module.models import User, MenuInfo, GlobalData
from user_module.rpc import user_pb2_grpc
from common.utils.id_util import md5


class UserHandler(user_pb2_grpc.UserServicer):

    def do_login(self, param, session):
        phone = param.get('phone')
        if not phone:
            return self.need_param('phone')
        password = param.get('password')
        if not password:
            return self.need_param('password')

        try:
            user = User.get(User.phone == phone, User.pwd == password)

            menu = []
            role = user.role.name
            self_menu = user.role.menus

            all_menus = MenuInfo.select().order_by(MenuInfo.sorted_index)
            menu_count = 0
            for m in all_menus:
                if '-' not in m.sorted_index:
                    continue
                if m.menu in self_menu or '***' in self_menu:
                    if m.sorted_index.endswith('-000'):
                        tmp = {
                            'menu': m.menu,
                            'menu_id': menu_count,
                            'icon': m.icon,
                            'sub_menu': [],
                        }
                        menu.append(tmp)
                        menu_count += 1
                    else:
                        menu[-1]['sub_menu'].append({
                            'menu': m.menu,
                            'icon': m.icon,
                            'url': m.url,
                        })

            try:
                key = '_user_' + user.phone
                data = GlobalData.select(GlobalData.value).where(GlobalData.key == key).get()
                cur_menu = json.loads(data.value)
            except BaseException as e:
                print(e)
                cur_menu = {
                    'menu': '开发者',
                    'sub_menu': '控制台日志',
                }

            session['user_phone'] = user.phone
            session['role'] = role
            session['user_id'] = user.id
            session['user_name'] = user.name

            return self.resp(1, http_result.RESULT_SUCCESS, {
                'phone': user.phone,
                'name': user.name,
                'role': role,
                'menus': json.dumps(menu),
                'cur_menu': cur_menu,
            })
        except BaseException as e:
            return self.resp(0, '用户名或密码错误', e.__str__())

    def do_logout(self, param, session):
        del session['role']
        del session['user_id']
        return self.resp(1, http_result.RESULT_SUCCESS)

    def do_query(self, param, session):
        result = []
        users = User.select()
        for u in users:
            result.append({
                'id': u.id,
                'name': u.name,
                'phone': u.phone,
                'role': u.role.name,
                'role_id': u.role_id,
            })

        return self.resp(1, http_result.RESULT_SUCCESS, result)

    def do_update(self, param, session):
        uid = param.get('id')
        if uid:
            user = User.get_by_id(uid)
        else:
            user = User()
        user.name = param.get('name')
        user.phone = param.get('phone')
        user.role = param.get('role')
        pwd = param.get('pwd')
        if pwd or not user.pwd:
            if not pwd:
                pwd = md5('123456')
            user.pwd = pwd
        try:
            user.save()
        except BaseException as e:
            if e.__str__().__contains__('Duplicate entry'):
                return self.resp(0, '手机号已存在')
            return self.resp(0, http_result.RESULT_FAIL, e.__str__())

        return self.resp(1, http_result.RESULT_SUCCESS)

    def do_delete(self, param, session):
        uid = param.get('id')
        if not uid:
            return self.need_param('id')
        User.delete_by_id(uid)
        return self.resp(1, http_result.RESULT_SUCCESS)
